'use strict';

const fs = require('fs');
const path = require('path');
const { Op } = require('sequelize');
const nodeXlsx = require('node-xlsx');
const moment = require('moment');

// 获取商标列表
exports.getTrademarkList = async (ctx) => {
  const { page = 1, pageSize = 10, keyword, trademark_status, application_date_start, application_date_end } = ctx.request.query;
  const offset = (parseInt(page) - 1) * parseInt(pageSize);
  const limit = parseInt(pageSize);

  // 构建查询条件
  const where = {};
  if (keyword) {
    where[Op.or] = [
      { trademark_name: { [Op.like]: `%${keyword}%` } },
      { registration_number: { [Op.like]: `%${keyword}%` } },
      { trademark: { [Op.like]: `%${keyword}%` } }
    ];
  }
  if (trademark_status) {
    where.trademark_status = trademark_status;
  }
  if (application_date_start && application_date_end) {
    where.application_date = {
      [Op.between]: [application_date_start, application_date_end]
    };
  }

  try {
    const { count, rows } = await ctx.app.fs.dc.models.TrademarkInfo.findAndCountAll({
      where,
      offset,
      limit,
      order: [['id', 'DESC']]
    });

    ctx.body = {
      code: 200,
      data: {
        list: rows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    };
  } catch (error) {
    console.error('获取商标列表错误:', error);
    ctx.body = {
      code: 500,
      message: '获取商标列表失败'
    };
  }
};

// 获取商标详情
exports.getTrademarkDetail = async (ctx) => {
  const { id } = ctx.params;
  
  try {
    const trademark = await ctx.app.fs.dc.models.TrademarkInfo.findByPk(id);
    
    if (!trademark) {
      ctx.body = {
        code: 404,
        message: '商标不存在'
      };
      return;
    }
    
    ctx.body = {
      code: 200,
      data: trademark
    };
  } catch (error) {
    console.error('获取商标详情错误:', error);
    ctx.body = {
      code: 500,
      message: '获取商标详情失败'
    };
  }
};

// 添加商标
exports.addTrademark = async (ctx) => {
  const trademarkData = ctx.request.body;
  
  try {
    const trademark = await ctx.app.fs.dc.models.TrademarkInfo.create(trademarkData);
    
    ctx.body = {
      code: 200,
      message: '添加商标成功',
      data: trademark
    };
  } catch (error) {
    console.error('添加商标错误:', error);
    ctx.body = {
      code: 500,
      message: '添加商标失败'
    };
  }
};

// 更新商标
exports.updateTrademark = async (ctx) => {
  const { id } = ctx.params;
  const trademarkData = ctx.request.body;
  
  try {
    const trademark = await ctx.app.fs.dc.models.TrademarkInfo.findByPk(id);
    
    if (!trademark) {
      ctx.body = {
        code: 404,
        message: '商标不存在'
      };
      return;
    }
    
    await trademark.update(trademarkData);
    
    ctx.body = {
      code: 200,
      message: '更新商标成功',
      data: trademark
    };
  } catch (error) {
    console.error('更新商标错误:', error);
    ctx.body = {
      code: 500,
      message: '更新商标失败'
    };
  }
};

// 删除商标
exports.deleteTrademark = async (ctx) => {
  const { id } = ctx.params;
  
  try {
    const trademark = await ctx.app.fs.dc.models.TrademarkInfo.findByPk(id);
    
    if (!trademark) {
      ctx.body = {
        code: 404,
        message: '商标不存在'
      };
      return;
    }
    
    await trademark.destroy();
    
    ctx.body = {
      code: 200,
      message: '删除商标成功'
    };
  } catch (error) {
    console.error('删除商标错误:', error);
    ctx.body = {
      code: 500,
      message: '删除商标失败'
    };
  }
};

// 批量删除商标
exports.batchDeleteTrademark = async (ctx) => {
  const { ids } = ctx.request.body;
  
  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    ctx.body = {
      code: 400,
      message: '请提供有效的ID数组'
    };
    return;
  }
  
  try {
    await ctx.app.fs.dc.models.TrademarkInfo.destroy({
      where: {
        id: {
          [Op.in]: ids
        }
      }
    });
    
    ctx.body = {
      code: 200,
      message: '批量删除商标成功'
    };
  } catch (error) {
    console.error('批量删除商标错误:', error);
    ctx.body = {
      code: 500,
      message: '批量删除商标失败'
    };
  }
};

// 导出商标
exports.exportTrademark = async (ctx) => {
  const { ids } = ctx.request.query;
  let where = {};
  
  if (ids) {
    const idArray = ids.split(',').map(Number);
    where.id = {
      [Op.in]: idArray
    };
  }
  
  try {
    const trademarks = await ctx.app.fs.dc.models.TrademarkInfo.findAll({
      where,
      order: [['id', 'DESC']]
    });
    
    // 准备导出数据
    const headers = ['商标名称', '商标', '注册号', '申请日期', '国际分类', '商标状态', '注册公告日期', '到期日期', '描述'];
    const data = [headers];
    
    trademarks.forEach(item => {
      const record = item.toJSON();
      data.push([
        record.trademark_name || '',
        record.trademark || '',
        record.registration_number || '',
        record.application_date ? moment(record.application_date).format('YYYY-MM-DD') : '',
        record.international_class || '',
        record.trademark_status || '',
        record.registration_announcement_date ? moment(record.registration_announcement_date).format('YYYY-MM-DD') : '',
        record.expiration_date ? moment(record.expiration_date).format('YYYY-MM-DD') : '',
        record.description || ''
      ]);
    });
    
    // 创建Excel buffer
    const buffer = nodeXlsx.build([{ name: '商标信息', data }]);
    
    // 生成文件
    const fileName = `商标信息_${moment().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
    const filePath = path.join(process.cwd(), 'app/downloadFiles', fileName);
    
    // 确保目录存在
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    
    // 写入文件
    fs.writeFileSync(filePath, buffer);
    
    // 设置响应头，提供下载
    ctx.attachment(fileName);
    ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    ctx.body = fs.createReadStream(filePath);
    
    // 设置定时删除文件
    setTimeout(() => {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }, 60 * 1000); // 1分钟后删除
  } catch (error) {
    console.error('导出商标错误:', error);
    ctx.body = {
      code: 500,
      message: '导出商标失败'
    };
  }
};

// 导入商标
exports.importTrademark = async (ctx) => {
  if (!ctx.request.files || !ctx.request.files.file) {
    ctx.body = {
      code: 400,
      message: '请上传文件'
    };
    return;
  }
  
  const file = ctx.request.files.file;
  
  try {
    // 解析Excel文件
    const workSheets = nodeXlsx.parse(file.path);
    
    if (!workSheets || workSheets.length === 0 || !workSheets[0].data || workSheets[0].data.length <= 1) {
      ctx.body = {
        code: 400,
        message: '文件中没有数据'
      };
      return;
    }
    
    const sheet = workSheets[0];
    const headers = sheet.data[0];
    const rows = sheet.data.slice(1);
    
    // 映射数据
    const trademarks = rows.map(row => {
      return {
        trademark_name: row[headers.indexOf('商标名称')] || '',
        trademark: row[headers.indexOf('商标')] || '',
        registration_number: row[headers.indexOf('注册号')] || '',
        application_date: row[headers.indexOf('申请日期')] ? moment(row[headers.indexOf('申请日期')]).format('YYYY-MM-DD') : null,
        international_class: row[headers.indexOf('国际分类')] || '',
        trademark_status: row[headers.indexOf('商标状态')] || '',
        registration_announcement_date: row[headers.indexOf('注册公告日期')] ? moment(row[headers.indexOf('注册公告日期')]).format('YYYY-MM-DD') : null,
        expiration_date: row[headers.indexOf('到期日期')] ? moment(row[headers.indexOf('到期日期')]).format('YYYY-MM-DD') : null,
        description: row[headers.indexOf('描述')] || ''
      };
    });
    
    // 批量创建
    await ctx.app.fs.dc.models.TrademarkInfo.bulkCreate(trademarks);
    
    // 删除临时文件
    if (fs.existsSync(file.path)) {
      fs.unlinkSync(file.path);
    }
    
    ctx.body = {
      code: 200,
      message: `成功导入${trademarks.length}条商标信息`
    };
  } catch (error) {
    console.error('导入商标错误:', error);
    ctx.body = {
      code: 500,
      message: '导入商标失败'
    };
  }
};
